package sopt.engSearch;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;


import org.xml.sax.SAXException;

import comm.parsers.DaumSearchSAXParserHandler;
import comm.util.SoptHashMap;

import statics.SoptVars;

public class DaumSearchProc {
	
	public static ArrayList getResultDaumSearch(String q,String category,int pageno,int length) throws UnsupportedEncodingException{
		ArrayList lt = null;
		if(pageno==0)pageno = 1;
		if(length==0)length = 5;
		
		
		//System.out.println("=========들어온 쿼리 값");
		//System.out.println(q);
		
		String reqUrl ="";
		
		if(category.equals(SoptVars.Menu_Category_Knowledge)){
			reqUrl = SoptVars.Daum_Knowledge_req_URL
				+"?apikey="+SoptVars.DaumSearchAPIKEY
				+"&range=complete&output=xml"
				+"&pageno="+pageno
				+"&result="+length
				+"&sort=accu"
				+"&q="+URLEncoder.encode(q, "UTF-8");
		}else if(category.equals(SoptVars.Menu_Category_Cafe)){
			reqUrl = SoptVars.Daum_Cafe_req_URL
			+"?apikey="+SoptVars.DaumSearchAPIKEY
			+"&output=xml"
			+"&pageno="+pageno
			+"&result="+length
			+"&sort=accu"
			+"&q="+URLEncoder.encode(q, "UTF-8");
	}else if(category.equals(SoptVars.Menu_Category_Board)){
			reqUrl = SoptVars.Daum_Board_req_URL
				+"?apikey="+SoptVars.DaumSearchAPIKEY
				+"&range=complete&output=xml"
				+"&pageno="+pageno
				+"&result="+length
				+"&sort=date"
				+"&q="+URLEncoder.encode(q, "UTF-8");
		}else if(category.equals(SoptVars.Menu_Category_Blog)){
			reqUrl = SoptVars.Daum_Blog_req_URL
				+"?apikey="+SoptVars.DaumSearchAPIKEY
				+"&range=complete&output=xml"
				+"&pageno="+pageno
				+"&result="+length
				+"&sort=date"
				+"&q="+URLEncoder.encode(q, "UTF-8");
		}else if(category.equals(SoptVars.Menu_Category_Image)){
			reqUrl = SoptVars.Daum_Image_req_URL
				+"?apikey="+SoptVars.DaumSearchAPIKEY
				+"&output=xml"
				+"&pageno="+pageno
				+"&result="+length
				+"&q="+URLEncoder.encode(q, "UTF-8");
			System.out.println(reqUrl);
		}else if(category.equals(SoptVars.Menu_Category_Video)){
			reqUrl = SoptVars.Daum_Videos_req_URL
				+"?apikey="+SoptVars.DaumSearchAPIKEY
				+"&output=xml"
				+"&pageno="+pageno
				+"&result="+length
				+"&q="+URLEncoder.encode(q, "UTF-8");
		}else{
			//잘못 될 경우에는 지식 검색으로~
			reqUrl = "http://apis.daum.net/search/knowledge?"
				+"apikey="+SoptVars.DaumSearchAPIKEY
				+"&range=complete&output=xml&result=5&sort=accu&q="
				+URLEncoder.encode(q, "UTF-8");
		}
		

		try {
			SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
			
			DaumSearchSAXParserHandler xmlHandler = new DaumSearchSAXParserHandler();
			
			
			parser.parse(reqUrl, xmlHandler);
			
			lt = xmlHandler.getItemList();
			
		} catch (ParserConfigurationException e) {
			return lt;
		} catch (IOException e) {
			return lt;
		} catch (SAXException e) {
			return lt;
		}
		
		//System.out.println("DAUM API가 리턴하는값 ");
		//System.out.println(lt.toString());
		
		return lt;
	}
	
	public static String getTranslatedSearchResult(ArrayList lt,int curpage,String category) throws UnsupportedEncodingException{
		String result = "";
		int count = 0;
		int totalcount = 0;
		if(lt!=null && lt.size()>0){
			SoptHashMap countHm = (SoptHashMap)lt.get(0);
			
			if(countHm.get("TOTALCOUNT")!=null)
				totalcount = Integer.parseInt(countHm.get("TOTALCOUNT").toString());
			if(curpage==1){
				result +="<div id='resultTotalCountHeader'>" +
						"<div id='resultHeaderCategory'>" +
						"<p>" +
						"Current Search Area : <b>" +
						category +
						"</b>" +
						"</p>" +
						"</div>" +
						"<div id='resultHeaderCount'>";
				count = lt.size();
				
				result+=
						"<p><span id='countOfResult'>"+count+"</span> Results" +
						" / Total:" +
						totalcount +
						"</p>" +
						"</div>" +
						"<div class='clear'></div>" +
						"</div>";
				
	       		
			}
			result +="<div id='searchResultTotalContainer'>";
			String transTitle = "";
       		String transDesc = "";
       		String link = ""; 
       		String author = "";
       		String pubdate = "";
       		String width="";
       		String height="";
       		String thumbnail="";
       		String cpname="";
       		String playtime="";
       		String playcount="";
       		String tag = "";
       		String player_url = "";
       			
			//기본적으로 검색은 Daum  ( 영문 페이지 번역 가능 )
			if(category.equals(SoptVars.Menu_Category_Knowledge) || category.equals(SoptVars.Menu_Category_Cafe) || category.equals( SoptVars.Menu_Category_Board) || category.equals( SoptVars.Menu_Category_Blog)){ //지식 검색
				for(int i=0;i<lt.size();i++){
		       		SoptHashMap tempHm = new SoptHashMap();
		       		tempHm = (SoptHashMap)lt.get(i);
		       		
		       		transTitle = TranslateProc.getTranslatedString(tempHm.get("TITLE").toString(),SoptVars.KOR_TO_ENG);
		       		transDesc = TranslateProc.getTranslatedString(tempHm.get("DESCRIPTION").toString(),SoptVars.KOR_TO_ENG);
		       		author = TranslateProc.getTranslatedString(tempHm.get("AUTHOR").toString(),SoptVars.KOR_TO_ENG);
		       		link = tempHm.get("LINK").toString();
		       		pubdate = tempHm.get("IMGPUBDATE").toString();
		       		
		       		
		       		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		       		Date date;
					try {
						date = format.parse(pubdate);
						format = new SimpleDateFormat("dd MMM yyyy HH:mm:ss",Locale.US);
						
						pubdate = format.format(date);
					} catch (ParseException e1) {
					}
		       		
		       		result +=
		       			"<div class='g'>" +
	       				"<p><a href='translatedPage.jsp?u="+URLEncoder.encode(link,"UTF-8")+"' target='_blank'>"+
	       				transTitle +
		       			"</a></p>" +
		       			"<div class='resultknowAuthor'>" +
       					author+
       					" - " +
       					pubdate+
       					"</div>"+
		       			"<p class='translatedDesc'>"+transDesc+"</p>";
		       		
		       		result +=
		       			"<p><a href='translatedPage.jsp?u="+URLEncoder.encode(link,"UTF-8")+"' target='_blank' class='linkGreen'>"+link+"</a></p>"+
       					"</div>";
		       	}
			}else if( category.equals( SoptVars.Menu_Category_Image ) ){ //이미지 검색
				for(int i=0;i<lt.size();i++){
					SoptHashMap tempHm = new SoptHashMap();
		       		tempHm = (SoptHashMap)lt.get(i);
		       		
		       		transTitle = TranslateProc.getTranslatedString(tempHm.get("TITLE").toString(),SoptVars.KOR_TO_ENG);
		       		link = tempHm.get("LINK").toString();
		       		pubdate = tempHm.get("IMGPUBDATE").toString();
		       		thumbnail = tempHm.get("THUMBNAIL").toString();
		       		width = tempHm.get("WIDTH").toString();
		       		height = tempHm.get("HEIGHT").toString();
		       		String host = link.substring(7);
		       		host = host.substring(0,host.indexOf("/"));
		       		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		       		Date date;
					try {
						date = format.parse(pubdate);
						format = new SimpleDateFormat("dd MMM yyyy HH:mm:ss",Locale.US);
						
						pubdate = format.format(date);
					} catch (ParseException e1) {
					}
		       		
		       		result +=
		       			"<div class='gImg'>" +
	       				"<p><a href='translatedPage.jsp?u="+link+"' target='_blank'>" +
	       						"<img class='gImgThumb' src='"+ thumbnail+ "' width='150' />"+
		       			"</a></p>" +
		       			"<p>" +
		       			transTitle +
		       			"</p>" +
		       			"<div class='resultknowAuthor'>" +
		       			width +"x"+height+
       					" - " +
       					pubdate+
       					"</div>";
		       		
		       		result +=
		       			"<p><a href='translatedPage.jsp?u="+link+"' target='_blank' class='linkGreen'>"+host+"</a></p>"+
       					"</div>";
		       	}
				
			}else if( category.equals( SoptVars.Menu_Category_Video ) ){ //동영상 검색
				result+="<div id='videoPlayerBg'>" +
						"<div id='videoPlayerHeader'><span id='videoPlayerTitle'></span><input type='button' value='close' onclick='closeVideoLayer()'/></div>" +
						"<div id='videoPlayerLayer'></div>" +
						"</div>";
				for(int i=0;i<lt.size();i++){
					SoptHashMap tempHm = new SoptHashMap();
		       		tempHm = (SoptHashMap)lt.get(i);
		       		
		       		transTitle = TranslateProc.getTranslatedString(tempHm.get("TITLE").toString(),SoptVars.KOR_TO_ENG);
		       		cpname = TranslateProc.getTranslatedString(tempHm.get("CPNAME").toString(),SoptVars.KOR_TO_ENG);
		       		tag = TranslateProc.getTranslatedString(tempHm.get("TAG").toString(),SoptVars.KOR_TO_ENG);
		       		author = TranslateProc.getTranslatedString(tempHm.get("AUTHOR").toString(),SoptVars.KOR_TO_ENG);
		       		link = tempHm.get("LINK").toString();
		       		pubdate = tempHm.get("IMGPUBDATE").toString();
		       		thumbnail = tempHm.get("THUMBNAIL").toString();
		       		
		       		playtime = tempHm.get("PLAYTIME").toString();
		       		playcount = tempHm.get("PLAYCNT").toString();
		       		player_url = tempHm.get("PLAYER_URL").toString();
		       		
		       		String host = link.substring(7);
		       		host = host.substring(0,host.indexOf("/"));
		       		SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		       		Date date;
					try {
						date = format.parse(pubdate);
						format = new SimpleDateFormat("dd MMM yyyy HH:mm:ss",Locale.US);
						
						pubdate = format.format(date);
					} catch (ParseException e1) {
					}
		       		int playtimeMin = Integer.parseInt(playtime)/60;
		       		String minute = "";
		       		if(playtimeMin<10)minute = "0"+ playtimeMin;
		       		int playtimeSec = Integer.parseInt(playtime)%60;
		       		String sec = "";
		       		if(playtimeSec<10)sec = "0"+ playtimeSec;
		       		result +=
		       			"<div class='gVid'>" +
	       				"<div class='gVidThumbBg'><a href='translatedPage.jsp?u="+link+"' target='_blank'>" +
	       						"<img class='gVidThumb' src='"+ thumbnail+ "' width='175' />"+
		       			"</a></div>" +
		       			"<div class='gVidDesc'><p><a href='translatedPage.jsp?u="+link+"' target='_blank'>" +
		       			transTitle +
		       			"</a>" +
		       			"</p>" +
		       			"<div class='resultknowAuthor'>" +
		       			author +" - "+cpname+
       					"-"+
       					pubdate+
       					"</div>" +
       					"<div class='gVidTag'>Play time: "+minute+":"+sec+
       					" / Play count: " +
       					playcount+
						" / TAG : " +
       					tag+
       					"</div>";
		       		
		       		result +=
		       			"<p><a class='linkGreen'>"+host+"</a></p>";
		       		
		       		if(player_url.length()>0)
		       			result+="<input type='button' title='"+transTitle+"' url='"+player_url+"' value='Direct View Video' onclick='javascript:showVideo(this)'/>";
		       		
   					result+="</div></div>";
		       	}
				
			}
			
			result+="</div>";
			if( category.equals( SoptVars.Menu_Category_Image ) )
				result+="<div class='clear'></div>";
		}
		
		return result;
		
	}
	

}
